#!/usr/bin/env python
import sys, os
sys.path.append(os.getcwd())

import argparse

import tempfile
def split_ssh_source (source):
    """_split_ssh_source(source) -> (user, host, path)
    split the values of a ssh source, guess the missing parts of user@host:path"""
    try:
        user,hostpart = source.split("@")
    except ValueError:
        user = getpass.getuser()
        try:
            host, path = source.split(":")
        except:
            path = "."
            host = source
    else:
        try:
            host, path = hostpart.split(":")
        except:
            path = "."
            host = hostpart
    return (user, host, path)

class SshMount(object):
    def __init__(self, target):
        self.user, self.host, self.path = split_ssh_source (target)
        self.mp = tempfile.mkdtemp()
        self.uid = os.getuid()
        self.port=22

    def __enter__(self):
        sshfs = "%s@%s:%s" % (self.user, self.host, self.path)
        status = os.system ('sshfs -p %d -o uid=%d -o intr "%s" "%s"' % (self.port, self.uid, sshfs, self.mp))
        if status == 0:        
            print "%s mounted as %s" % (sshfs, self.mp)
        else:
            os.rmdir (self.mp)

        return self.mp

    def __exit__(self, exc_type, exc_value, traceback):
        if os.path.exists (self.mp):
            os.system ("fusermount -u -z " + self.mp)
            #os.system ("umount " + self.mp)
            os.rmdir (self.mp)
